/** 
 * 使用方法：
 * 1.脚本顶部引入 const app = getApp();
 * 2.Utils.$router.push(name,params,type)
 * -1）params为传入参数和值，如果params有值，将存在本地存储中
 * -2）如果type（默认为params）为query时，参数会拼接到url后面
 * 3.Utils.$router.reLaunch(name,params,type)//打开到应用内的某个页面,可跳转到Tabbar页面
 * 4.Utils.$router.redirect(name,params,type)//打开到应用内的某个页面,不可重定向到Tabbar页面
 * 5.Utils.$router.switchTab(name)//跳转指定的tab页
 * 6.Utils.$router.back(deltah,params)//返回上n级页面
 * 7.Utils.$router.backHome(params)//返回到首页
 * 8.Utils.$router.webviewRedirect(name, params)//跳转到webview页面
 * 9.Utils.$router.openUrlScheme //传入url结构解析后跳转
 * 10.链式调用success，fail，complete，
 *  例：Util.$router.push("mine")
        .success(res => {
          console.log("success: ", res)
        })
        .fail(err => {
          console.log("fail: ", res)
        })
        .complete(_ => {
          console.log("complete")
        })
*/

const symbol = {
  reLaunch: Symbol(),
  redirect: Symbol(),
  switchTab: Symbol(),
}

export default class Router {

  /**
   * constructor 🚀
   */
  constructor() {
    // 当前页面携带的参数 (缓存在storage中)
    this.params = null

    // 当前页面携带的参数 (在query中)
    this.query = null

    this.callbacks = {}

    this.success = function (onSuccess) {
      this.callbacks.onSuccess = onSuccess
      return this
    }
    this.fail = function (onFail) {
      this.callbacks.onFail = onFail
      return this
    }
    this.complete = function (onComplete) {
      this.callbacks.onComplete = onComplete
      return this
    }
  }

  /******** Public ********/

  /**
   * 保留当前页面，跳转到应用内的某个页面。但是不能跳到 tabbar 页面
   * @param name
   * @param params
   * @returns {*}
   */
  push(name, params = null, type = 'params') {

    // const page = isFullPath ? { url: name, name: name}:this.getPageFor(name)
    const page = {
      url: name,
      name: name
    }

    if (!page) {
      throw Error(`!! Not found page ->：[${name}] !!`)
      return
    }

    this.currentPage = page

    if (params) {
      const key = `router-${page.name}-params`
      wx.setStorageSync(key, params)
      this.params = this._getParams(key)
    } else {
      this.params = null
    }

    if (type === 'query') {
      this.params = {}
      page.url += "?"
      for (let key in params) {
        console.log("key: ", key)
        page.url += `${key}=${params[key]}&`
        this.params[key] = params[key]
      }
      page.url = page.url.slice(0, -1)
      console.log("this.params", this.params)
    }

    const [, , obj] = Array.from(arguments)
    const that = this
    let f = wx.navigateTo
    if (obj && Object.is(obj.fn, symbol.reLaunch)) {
      f = wx.reLaunch
    }
    if (obj && Object.is(obj.fn, symbol.redirect)) {
      f = wx.redirectTo
    }
    if (obj && Object.is(obj.fn, symbol.switchTab)) {
      f = wx.switchTab
    }
    f({
      url: page.url,
      ...that._getFunc()
    })
    return this
  }

  /**
   * 关闭所有页面，打开到应用内的某个页面 可传递参数 可跳转到Tabbar页面
   * @param name
   * @param params
   */
  reLaunch(name, params = null, type = 'params') {
    return this.push(name, params, {
      fn: symbol.reLaunch
    }, type)
  }

  /**
   * 关闭所有页面，打开到应用内的某个页面 可传递参数 不可重定向到Tabbar页面
   * @param name
   * @param params
   */
  redirect(name, params = null, type = 'params') {
    return this.push(name, params, {
      fn: symbol.redirect
    }, type)
  }

  /**
   * 跳转指定的tab页
   * @param name
   * @returns {*}
   */
  //xxk://switchTab/pages/card/index
  switchTab(name) {
    return this.push(name, null, {
      fn: symbol.switchTab
    })
  }

  /**
   * 关闭当前页面，返回上一页面或多级页面。 没有参数 代表返回上一页
   * @param delta
   * @param params
   */
  back(delta = 1, params = null) {
    if (params) {
      const key = `router-${this._currentPage.name}-params`
      wx.setStorageSync(key, params)
      this.params = this._getParams(key)
    } else {
      this.params = null
    }
    wx.navigateBack({
      delta,
      ...this._getFunc()
    })

    return this
  }

  /**
   * 关闭所有页面返回到首页
   * @param params
   */
  backHome(params = null) {
    // return this.back(Number.MAX_SAFE_INTEGER, params)
    return this.reLaunch('/pages/index/index')
  }

  /**
   * 跳转到webview页面
   * @param name
   * @param params
   */

  webviewRedirect(url = null, title = '') {
    return this.push('/pages/web-view/index', {
      title: title,
      url: encodeURIComponent(url)
    }, 'query')
  }

  /** 
   * 跳转到其他小程序
   * @param url
   */
    //调整小程序数据格式,appId要先加到app.json中
    //'xxk://navigateToMiniPrograms??appId=wx636830278bc7b5f4@path=/pages/consultant?id=1@envVersion=release@extraData={"fromwhere":"aolai"}'
  navigateToMiniProgramRedirect(OBJ) {
    let search = OBJ.split('??')[1]
    let appId = this._getQueryString('appId',search)
    let path = this._getQueryString('path',search)
    let extraData = JSON.parse(this._getQueryString('extraData',search))
    let envVersion = this._getQueryString('envVersion',search) || 'release'

    wx.navigateToMiniProgram({
      appId: appId,
      path: path,
      extraData: extraData,
      envVersion: envVersion
    })
    return this
  }


  /** 
   * 传入url结构解析后跳转
   * @param url
   */

  openUrlScheme(url = null, title = '') {
    if (url.indexOf('http') > -1) {
      this.webviewRedirect(url, title)
      }else if(url.indexOf('xxk://navigateToMiniProgram')>-1){
      this.navigateToMiniProgramRedirect(url)
    } else if (url.indexOf('xxk://switchTab')>-1) {
       this.switchTab(url.split('switchTab')[1])
      // } else if(url.indexOf('ixm://reLaunch')>-1) {
      //   this.reLaunch(url.split('reLaunch')[1])
      // } else if(url.indexOf('ixm://redirectTo')>-1) {
      //   this.redirect(url.split('redirectTo')[1])
      // } else if(url.indexOf('ixm://navigateTo')>-1){
      //   this.push(url.split('navigateTo')[1])
      // } else if(url.indexOf('ixm://navigateBack')>-1){
      //   this.back(url.split('navigateBack/')[1])
    } else {
      this.push(url)
    }
    return this
  }



  /******** Private ********/


  /**
   * 获取函数
   * @returns {{fail: fail, success: success, complete: complete}}
   * @private
   */
  _getFunc() {
    let that = this
    return {
      success: function (res) {
        if (that.callbacks.onSuccess) that.callbacks.onSuccess(res)
      },
      fail: function (err) {
        if (that.callbacks.onFail) that.callbacks.onFail(err)
      },
      complete: function () {
        if (that.callbacks.onComplete) that.callbacks.onComplete()
      }
    }
  }

  /**
   * 获取当前跳转的页面的携带的参数
   * @param key
   * @returns {*}
   * @private
   */
  _getParams(key) {
    return wx.getStorageSync(key)
  }

  /** 
   * 获取url的query值
   * @param name
   * @private
   */

  _getQueryString = (name, url) => {
    if (url.indexOf(name) > -1) {
      var reg = new RegExp('(^|@)' + name + '=([^@]*)(@|$)', 'i');
      var r = url.match(reg)
      if (r != null) {
        return unescape(r[2]);
      }
    }
    return null;
  }
}